<template>
  <div id="track_map"></div>
  <div class="distance-info" v-if="currentEvent">
    <h2 style="color:rgb(80, 97, 109)">{{ totalDistance }} km</h2> 
  </div>
  <div class="control-buttons">
    <button @click="startTrack">开始</button>
    <button @click="pauseTrack" :disabled="isPaused">暂停</button>
    <button @click="restartTrack">重启</button>
  </div>
  <div class="current-event-info" v-if="currentEvent"  >  
    <h2 style="color:rgb(80, 97, 109);">事件</h2>  
    <!-- <p>时间: {{ currentEvent.time }}</p>   -->
    <p style="  text-indent: 2em;font-size: 19px;line-height: 1.8; ">{{ currentEvent.description }}</p>  
  </div>  
  <div class="times" v-if="currentEvent">
       <h2 style="color:rgb(80, 97, 109)"> {{ currentEvent.time }}</h2>  
    </div>
    <div class="place" v-if="currentEvent">
       <h4 style="color:rgb(80, 97, 109)"> {{ currentEvent.next }}</h4>  
    </div>
  
</template>

<script setup>
import { onMounted, onUnmounted, ref,computed } from 'vue';
import AMapLoader from '@amap/amap-jsapi-loader';
import data from "@/assets/json/最终版轨迹路线坐标.json";
import events from "@/assets/json/轨迹事件.json";
import { useStore } from 'vuex';  

let map = null;
let polyline = null;
let timer = null;
const totalDistance = ref(0);
const isPaused = ref(false);
const trackPoints = ref([]);
let currentIndex = 0;
let startMarker = null; // 新增：用于表示轨迹起点的标记  

// 存储事件标记的数组
let eventMarkers = [];

const store = useStore();  
// 自定义图标URL  
    const customIconUrl = 'https://cdn-icons-png.flaticon.com/128/11578/11578283.png'; // 替换为您的自定义图标URL  
//当前事件
const currentEvent = computed(() => store.state.currentEvent);  

async function initMap() {
  try {
    const AMap = await AMapLoader.load({
      key: '2c79a7f8c05647f33b075ee487531840',
      version: '2.0',
      plugins: ['AMap.Scale'],
    });
    map = new AMap.Map('track_map', {
      viewMode: '3D',
      zoom: 10,
      center: new AMap.LngLat(data.features[0].geometry.coordinates[0][0], data.features[0].geometry.coordinates[0][1]),
      mapStyle: 'amap://styles/whitesmoke',
      pitch: 50,
    });

    map.on('complete', function () {
      const skyLayer = map.getLayers().find(layer => layer.CLASS_NAME === "AMap.SkyLayer");
      if (skyLayer) {
        skyLayer.hide();
      }
    });

    trackPoints.value = data.features[0].geometry.coordinates.map(coord => {
      if (coord[0] === undefined || coord[1] === undefined || isNaN(coord[0]) || isNaN(coord[1])) {
        console.error('Invalid coordinates:', coord);
        return null;
      }
      return new AMap.LngLat(coord[0], coord[1]);
    }).filter(pt => pt !== null);

    if (trackPoints.value.length === 0) {
      console.error('No valid track points to display.');
      return;
    }

    polyline = new AMap.Polyline({
      path: trackPoints.value,
      strokeColor: '#425066',
      strokeWeight: 6,
      lineJoin: 'round',
      lineCap: 'round',
      showDir: true
    });
    polyline.setMap(map);
    // 添加起始标记  
    // 添加起始标记  
startMarker = new AMap.Marker({  
  position: trackPoints.value[0], // 起点坐标  
  title: '起点', // 标记的标题  
   icon: customIconUrl, // 使用自定义图标  
  offset: new AMap.Pixel(-15, -15)  ,
   scale: 0.4 // 设置缩放比例（1.5倍）  
});  

// 将标记添加到地图  
startMarker.setMap(map); // 确保添加到地图

  } catch (e) {
    console.error(e);
  }
}



// 添加事件标记
function addEventMarker(event) {
  const marker = new AMap.Marker({
    position: new AMap.LngLat(event.position[0], event.position[1]),
    // title: event.place,
    content: `<div style="background-color: rgba(29, 43, 76, 0.8); padding: 5px; border-radius: 3px; box-shadow:  5px 6px rgba(35, 29, 29, 0.2); color: #fff; font-family: 'Arial', sans-serif; font-size: 14px;">${event.place}</div>`,
    offset: new AMap.Pixel(-50, -50)
  });
  marker.setMap(map);
  eventMarkers.push(marker);
}

// 清除事件标记
function clearEventMarkers() {
  eventMarkers.forEach(marker => marker.setMap(null));
  eventMarkers = [];
}




//找到匹配的经纬度
function findEventByPosition(position) {
  const events = store.state.events;
  let foundEvent = null;

  // 设置一个距离阈值，例如50000米（约50公里）
  const distanceThreshold = 400;

  events.forEach(event => {
    const eventPosition = new AMap.LngLat(event.position[0], event.position[1]);
    const currentPosition = new AMap.LngLat(position.lng, position.lat);
    const distance = AMap.GeometryUtil.distance(eventPosition, currentPosition);

    if (distance < distanceThreshold) {
      foundEvent = event;
      // 找到最近的事件后，就停止搜索
      return;
    }
  });

  return foundEvent;
}

function calculateTotalDistance(points) {
  let totalDist = 0;
  for (let i = 0; i < points.length - 1; i++) {
    totalDist += AMap.GeometryUtil.distance(points[i], points[i + 1]);
  }
  return (totalDist / 1000).toFixed(2); // 转换为公里并保留两位小数  
}


function drawTrack() {  
  if (isPaused.value || currentIndex >= trackPoints.value.length - 1) return;  

  // 更新多段线的路径  
  polyline.setPath(trackPoints.value.slice(0, currentIndex + 1));  
  map.setCenter(trackPoints.value[currentIndex]);  

  // 更新汽车标记的位置  
  const currentLatLng = trackPoints.value[currentIndex];  
  startMarker.setPosition(currentLatLng);  // 更新标记的位置  

  totalDistance.value = calculateTotalDistance(polyline.getPath());  
  
  const currentPosition = {  
    lat: currentLatLng.lat,  
    lng: currentLatLng.lng,  
  };  
  const event = findEventByPosition(currentPosition);  
  
  if (event) {  
    store.dispatch('setCurrentEvent', event);  
    addEventMarker(event); // 添加事件标记  
  } else {  
    const lastEvent = store.state.lastEvent;  
    if (lastEvent) {  
      store.dispatch('setCurrentEvent', lastEvent); // 保持上一个事件  
    } else {  
      store.dispatch('clearCurrentEvent');  
    }  
  }  

  currentIndex++;  

  if (currentIndex < trackPoints.value.length) {  
    timer = setTimeout(drawTrack, 100);  
  }  
}

function startTrack() {
  if (!isPaused.value) {
    currentIndex = 0;  // 重置索引  
  }
  isPaused.value = false;  // 确保处于运行状态  
  drawTrack();  // 开始绘制轨迹  
}

function pauseTrack() {
  isPaused.value = true; // 暂停动画  
  if (timer) clearTimeout(timer); // 清除定时器  
}

function restartTrack() {
  pauseTrack();  // 先暂停  
  currentIndex = 0; // 重置索引  
  totalDistance.value = 0; // 重置总距离  
  polyline.setPath([]); // 清除路径  
  startTrack(); // 重新开始  
}

onMounted(() => {
  initMap();
});

onUnmounted(() => {
  if (timer) clearTimeout(timer);
  if (polyline) polyline.setMap(null);
  if (map) map.destroy();
  if (startMarker) startMarker.setMap(null); // 清除起始标记  
   clearEventMarkers(); // 清除事件标记
});  
</script>

<style>
#track_map {
  width: 100%;
  height: 100%;
}

.distance-info {
  position: absolute; 
  top: 30%;
  left: 5%;
  width: 11.6%;
  z-index: 1000;
  background:  rgba(242,242,242,0.94);
  padding: 12px;
  /* border-radius: 13px; */
  /* font-size: 24px; */
  border-radius: 4px;  
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);  
  text-align: center
}
.times{
   position: absolute; 
   width: 11.6%;
  top: 15%;
  left: 5%;
  z-index: 1000;
  background: rgba(242,242,242,0.94);;
  padding: 12px;
  /* border-radius: 13px; */
  /* font-size: 22px; */
  line-height: 2;
  border-radius: 4px;  
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);  

}

.control-buttons {
  position: absolute;
  /* 确保控制按钮容器定位 */
  top: 90%;
  /* 设定整体控制按钮容器的顶部位置 */
  left: 85%;
  z-index: 1000;
}

.control-buttons button {
  margin: 4px;
  padding: 6px 12px;
  background-color: rgb(214, 236, 240);
  /* 按钮背景颜色 */
  color: rgb(33, 2, 71);
  /* 按钮文字颜色 */
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.control-buttons button:disabled {
  background-color: #ccc;
  /* 灰色 */
  cursor: not-allowed;
}

.current-event-info {  
  width: 28%;
  position: absolute;  
  top: 15%;  
  left: 65%;  
  background: rgba(242,242,242,0.94);;  
  padding: 10px;  
  border-radius: 4px;  
  box-shadow: 0 2px 5px rgba(129,106,106,0.31);  
  z-index: 12; /* Ensure it is above the map */  
}  
.place{
  width: 28%;
  position: absolute;  
  top: 50%;  
  left: 50%;  
}

</style>



<!-- <template>
  <div id="track_map"></div>
</template>

<script setup>
import { onMounted, onUnmounted } from 'vue';
import AMapLoader from '@amap/amap-jsapi-loader';
import data from "@/assets/json/新路径.json";

let map = null;
let marker = null;
let polyline = null;

onMounted(() => {
  window._AMapSecurityConfig = {
    securityJsCode: 'b132114373c23654eeaae0e171f851d6',
  };

  AMapLoader.load({
    key: '2c79a7f8c05647f33b075ee487531840',
    version: '2.0',
    plugins: ['AMap.Scale'],
  })
    .then((AMap) => {
      map = new AMap.Map('track_map', {
        viewMode: '3D',
        zoom: 11,
        center: data.features[0].geometry.coordinates[0], // 设置地图中心点为轨迹的第一个点
        mapStyle: 'amap://styles/whitesmoke',
        pitch: 50,
      });

      // 提取轨迹点
      const trackPoints = data.features[0].geometry.coordinates.map(coord => {
        return new AMap.LngLat(coord[0], coord[1]);
      });

      // 创建轨迹线
      polyline = new AMap.Polyline({
        path: trackPoints,
        strokeColor: '#FF0000', // 线颜色
        strokeWeight: 6, // 线宽
      });
      polyline.setMap(map);

      // 创建标记
      marker = new AMap.Marker({
        map: map,
        position: trackPoints[0], // 初始位置
        icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png', // 标记图标
        offset: new AMap.Pixel(-26, -13),
      });

      // 动画移动标记
      moveMarker(trackPoints);
    })
    .catch((e) => {
      console.log(e);
    });
});

// 移动标记的函数
function moveMarker(points) {
  let index = 0;
  marker.moveAlong(points, 200); // 沿轨迹移动标记，速度为200
}

onUnmounted(() => {
  map?.destroy();
});
</script>

<style>
#track_map {
  width: 100%;
  height: 100%;
}
</style> -->


// <!-- <template>
//   <div id="track_map"> 
//   </div>
// </template>

// <script setup>
// import { onMounted, onUnmounted, ref } from "vue";
// import AMapLoader from "@amap/amap-jsapi-loader";
// import data from "@/assets/json/总路径.json";

// let map = null;
// let marker = null;
// let markerMoving = false; // 标记是否正在移动

// onMounted(() => {
//   window._AMapSecurityConfig = {
//     securityJsCode: "b132114373c23654eeaae0e171f851d6",
//   };
//   AMapLoader.load({
//     key: "2c79a7f8c05647f33b075ee487531840",
//     version: "2.0",
//     plugins: ["AMap.Scale"],
//   })
//     .then((AMap) => {
//       map = new AMap.Map("track_map", {
//         viewMode: "3D",
//         zoom: 11,
//         center: [113.23682746584473, 23.106303334998117],
//         mapStyle: 'amap://styles/whitesmoke',
//         pitch: 50,
//       });

//       map.on('complete', function () {
//         const skyLayer = map.getLayers().find(layer => layer.CLASS_NAME === "AMap.SkyLayer");
//         if (skyLayer) {
//           skyLayer.hide();
//         }
//       });

//       const coordinates = data.features[0].geometry.coordinates;

//       const polyline = new AMap.Polyline({
//         path: coordinates,
//         isOutline: true,
//         outlineColor: '#ffeeee',
//         borderWeight: 2,
//         strokeColor: "#3366FF",
//         strokeOpacity: 1,
//         strokeWeight: 6,
//         strokeStyle: "solid",
//         lineCap: 'round',
//         lineJoin: 'round',
//         geodesic: true,
//       });

//       polyline.setMap(map);

//       marker = new AMap.Marker({
//         map: map,
//         position: coordinates[0],
//         icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
//         offset: new AMap.Pixel(-13, -30)
//       });

//       // 开始动画
//       marker.moveAlong(coordinates, 200); // 速度设置为200像素/秒

//       // 动画完成后的回调函数
//       marker.on('movealong', function(e) {
//         if (!markerMoving) return; // 如果标记不再移动，则不执行
//         marker.setPosition(coordinates[0]); // 重置标记位置到路径的起点
//         marker.moveAlong(coordinates, 200); // 重新开始动画
//       });

//       markerMoving = true; // 标记开始移动
//     })
//     .catch((e) => {
//       console.log(e);
//     });
// });

// onUnmounted(() => {
//   markerMoving = false; // 停止标记移动
//   map?.destroy();
// });
// </script>

// <style>
// #track_map {
//   width: 100%;
//   height: 100%;
// }
// </style>
//  -->










<!-- <template>
   <div id="track_map"> 
  </div>
 </template>

<script setup>
import { onMounted, onUnmounted } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";
import data from "@/assets/json/路径.json";
let map = null;

onMounted(() => {
  window._AMapSecurityConfig = {
    securityJsCode: "b132114373c23654eeaae0e171f851d6",
  };
  AMapLoader.load({
    key: "2c79a7f8c05647f33b075ee487531840", // 申请好的Web端开发者Key，首次调用 load 时必填
    version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: ["AMap.Scale"], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
  })
    .then((AMap) => {
      map = new AMap.Map("track_map", {
        // 设置地图容器id
        viewMode: "3D", // 是否为3D地图模式
        zoom: 11, // 初始化地图级别
        center: [116.397428, 39.90923],
        mapStyle: 'amap://styles/whitesmoke', // 初始化地图中心点位置
        pitch: 50,
      });
      // 地图加载完成后隐藏天层
      map.on('complete', function () {
        const skyLayer = map.getLayers().find(layer => layer.CLASS_NAME === "AMap.SkyLayer");
        if (skyLayer) {
          skyLayer.hide();
        }
      });

   console.log(map); // 确保 map 实例被创建
       })
       
    .catch((e) => {
      console.log(e);
    });
 
});

onUnmounted(() => {
  map?.destroy();
});
 </script>

 <style>
 #track_map {
   width: 100%;
   height: 100%;
 }
 </style> -->






// <!-- <template>
//   <div id="track_map">
//     <button @click="startAnimation">开始动画</button>
//     <button @click="stopAnimation">停止动画</button>
//   </div>
// </template>

// <script setup>
// import data from "@/assets/json/西江(广州-梧州段).geojson";
// import { onMounted, onUnmounted } from "vue";
// import AMapLoader from "@amap/amap-jsapi-loader";

// let map = null;

// onMounted(() => {
//   window._AMapSecurityConfig = {
//     securityJsCode: "「b132114373c23654eeaae0e171f851d6」",
//   };
//   AMapLoader.load({
//     key: "	2c79a7f8c05647f33b075ee487531840", // 申请好的Web端开发者Key，首次调用 load 时必填
//     version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
//     plugins: ["AMap.Scale"], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
//   })
//     .then((AMap) => {
//       map = new AMap.Map("s_map", {
//         // 设置地图容器id
//         viewMode: "3D", // 是否为3D地图模式
//         zoom: 11, // 初始化地图级别
//         center: [116.397428, 39.90923],
//         mapStyle: 'amap://styles/whitesmoke', // 初始化地图中心点位置
//         pitch: 50,
//       });
//       // 地图加载完成后隐藏天层
//       map.on('complete', function () {
//         const skyLayer = map.getLayers().find(layer => layer.CLASS_NAME === "AMap.SkyLayer");
//         if (skyLayer) {
//           skyLayer.hide();
//         }
//       });



//    console.log(map); // 确保 map 实例被创建
//        })
       
//     .catch((e) => {
//       console.log(e);
//     });
 
// });

// onUnmounted(() => {
//   map?.destroy();
// });

// </script>

// <style>
// #track_map {
//   width: 100%;
//   height: 100%;
//   display: flex;
//   justify-content: center;
//   align-items: center;
//   font-family: 'Arial', sans-serif;
// }
// </style> -->
